package com.wangbo.box.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 动态代理 依赖接口
 */
public class DynamicProxyPattern {

    interface Subject {
        int invoke(int num);
    }

    static class RealSubject implements Subject {
        @Override
        public int invoke(int num) {
            System.out.println("this is realSubject invoke");
            return num;
        }
    }

    static class ProxyHandler implements InvocationHandler{
        private Object object;

        public ProxyHandler(Object object) {
            this.object = object;
        }
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            System.out.println("preInvoke");
            Object result = method.invoke(object, args);
            System.out.println("postInvoke");
            return result;
        }
    }

    public static void main(String[] args) {
        Subject subject = new RealSubject();
        ProxyHandler proxyHandler = new ProxyHandler(subject);
        Subject proxySubject = (Subject) Proxy.newProxyInstance(subject.getClass().getClassLoader(), subject.getClass().getInterfaces(), proxyHandler);
        System.out.println(proxySubject.invoke(1));
    }
}
